import React, { Component } from 'react';
import { Form, Input, DatePicker,Select } from 'antd';
import { connect } from 'dva';
import AntdFormItem from '@/components/AntdFormItem';
import AntdDatePicker from '@/components/AntdDatePicker';
import AntdInput from '@/components/AntdInput';
import AdSelect from '@/components/AdSelect';
import AntdForm from '@/components/AntdForm';
import AdModal from '@/components/AdModal';
import SearchSelect from '@/components/SearchSelect';
import moment from 'moment';
import router from 'umi/router';
import { formItemFragement, queryDict ,formatPrice} from '@/utils/common';
import { allDictList } from '@/utils/constans';
import { columnsDriver } from '@/pages/Common/common';
import { emptyTypeList, allDispatchType, selectArchivesList, routeUrl,driverType,renderTableAdSelect } from './utils';

import styles from './archives.less';
const { Option } = Select;
const { TextArea } = Input;
const dateFormat='YYYY-MM-DD';
const dateFormatByM = 'YYYY-MM';
const { MonthPicker } = DatePicker;

@connect(({ Archives, component }) => ({
  Archives,
  emptyDetails: Archives.emptyDetails,
  dictObject: component.dictObject,
}))
@Form.create()
export default class EmptyArchives extends Component {
  constructor(props) {
    super(props);
    this.state = {
      drivers: [],
      driverType:'HW01',
    };
  }
  
  componentDidMount() {
    let allDict = [
      allDictList.emptyType_ZG,
      allDictList.emptyType_QS,
      allDictList.emptyType,
      allDictList.driverType,
      allDictList.currencyType
    ];
    queryDict({ props: this.props, allDict });
    const { detailId, onRef } = this.props;
    if (detailId) this.getEmptyDetails();
    if (onRef) onRef(this);
  }
  getEmptyDetails = () => {
    const { dispatch, detailId } = this.props;
    dispatch({
      type: allDispatchType.selectEmptyDetails,
      payload: { id: detailId },
      callback: data => {
        const driverIdObj =
          data.driverIds &&
          data.driverIds.map(v => {
            return { id: v };
          });
        this.setState({
          drivers: driverIdObj || [],
        });
      },
    });
  };
  saveInfo = () => {
    const { form, dispatch, detail, formValues, modalEmpty, detailId } = this.props;
    const { drivers } = this.state;

    form.validateFieldsAndScroll((err, values) => {
      if (err) return;
      const { driverIds, settlementDate, ...params } = values;
      //司机
      if (drivers.length > 0) {
        params.driverIds = drivers.map(v => {
          return v.id;
        });
      }
      params.settlementDate = settlementDate ? moment(settlementDate).format(dateFormatByM) : '';
      if (detailId) params.id = detailId;
      dispatch({
        type: allDispatchType.emptyArchives,
        payload: params,
        callback: data => {
          if (modalEmpty) modalEmpty();
          if (detailId) this.getEmptyDetails();
          selectArchivesList({ payload: formValues, props: this.props });
          if (!detailId) router.push(`${routeUrl.editEmpty}/${data}`);
        },
      });
    });
  };
  getValue = (values, type) => {
    
    const { dispatch, dictObject, form } = this.props;
    const {driverType,drivers}=this.state
    this.setState({
      [type]: values,
    });
    if(type=='driverType'){

      form.setFieldsValue({ currencyType: values=='HW01'? 'HKD':'CNY' })
      // form.setFieldsValue({ drivers:'' })
      form.setFieldsValue({ emptyType:'' })
      form.setFieldsValue({ abnormalAmount:'' })
    }
    if(type=='emptyType'){
      let empty= driverType=='HW01'?dictObject[allDictList.emptyType_ZG]:dictObject[allDictList.emptyType_QS]
      let obj = empty.find(item => item.code === values) 
      // console.log('obj----',obj,values,empty)
      
      form.setFieldsValue({ abnormalAmount: obj.remarks }); 
      
    }
  };

 
  render() {
    const { drivers,driverType } = this.state;
    const {
      dictObject,
      detailId,
      emptyDetails,
      form: { getFieldDecorator },
      visible,
      disabled,
      modalEmpty,
      mode,
    } = this.props;
    const detail = emptyDetails[detailId] || {};
    const commonParams = {
      getFieldDecorator,
    };
    const editPageParams = {
      title: detail.id || '新增车次',
      panelValue: [{ key: '基础信息' }],
    };
    const prefixSelector = getFieldDecorator('currencyType', {
      initialValue:'HKD',

    })(
     
      <Select disabled={true} style={{width: 90 }}>
        {dictObject[allDictList.currencyType] &&
          dictObject[allDictList.currencyType].map(item => (
            <Option key={item.code}>{item.value}</Option>
          ))}
      </Select>
    );
    console.log('异常类型=========》',detail.emptyType,dictObject[allDictList.emptyType],)
    const formItem = [
      [
        <AntdFormItem
          label="司机类型"
          code="driverType"
          rules={[{ required: true }]}
          initialValue={driverType}
          {...commonParams}
        >
          <AdSelect
            disabled={disabled}
            data={dictObject[allDictList.driverType]}
            payload={{ code: allDictList.driverType }}
            onChange={val => this.getValue(val, 'driverType')} // 获取选中值
            // filterValue={['MA_CAR']}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="司机"
          code="driverIds"
          initialValue={drivers}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <SearchSelect
            dataUrl="tms/tms-driver-archives/selectDriverList"
            url="tms/tms-driver-archives/selectDriverView_s"
            multiple={false} // 是否多选
            selectedData={drivers} // 选中值
            columns={columnsDriver} // 表格展示列
            onChange={val => this.getValue(val, 'drivers')} // 获取选中值
            id="ArchivesOperate_2"
            disabled={disabled}
            allowClear={false}
            // scrollX={350}
            placeholder="请输入"
             payload={{ mdsCompanyId: driverType }}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="异常类型"
          code="emptyType"
          rules={[{ required: true }]}
          initialValue={
            detail.emptyType}
          {...commonParams}
        >
          <AdSelect 
            disabled={disabled} 
            isExist={true} 
            data={driverType?
             ( driverType=='HW01'? dictObject[allDictList.emptyType_ZG]:dictObject[allDictList.emptyType_QS])
              :dictObject[allDictList.emptyType]
            } 
            onChange={val => this.getValue(val, 'emptyType')} // 获取选中值
          />
         </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="异常金额"
          code="abnormalAmount"
          rules={[{ required: true }]}
          initialValue={formatPrice(detail.abnormalAmount)}
          {...commonParams}
        >
          <Input addonBefore={prefixSelector} placeholder="" disabled={disabled} />
         
        </AntdFormItem>,
        // <AntdFormItem
        //   label="币种"
        //   code="currencyType"
        //   initialValue={'HKD'}
        //   {...commonParams}
        // >
        //   <AntdInput disabled={true} />
        
        // </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="结算周期"
          code="settlementDate"
          rules={[{ required: true }]}
          initialValue={
            detail && detail.settlementDate ? moment(detail.settlementDate, dateFormatByM) : null
          }
          {...commonParams}
        >
          <MonthPicker disabled={disabled} style={{ width: '100%' }} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="发车时间"
          code="transportStartTime"
          rules={[{ required: true }]}
          initialValue={
            detail && detail.transportStartTime ? moment(detail.transportStartTime, dateFormat) : null
          }
          {...commonParams}
        >
         <AntdDatePicker
            disabled={disabled}
            // onChange={e => this.changeHundredConsump(e, 'oilTime')}
          />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label="关联车次号"
          initialValue={detail.mergeTrainNo}
          rules={[{ required: true }]}
          code="mergeTrainNo"
          {...commonParams}
        >
          <AntdInput placeholder="请输入" disabled={disabled} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem 
          label="备注" code="remark" initialValue={detail.remark} {...commonParams}
          rules={[{ required: true }]}
          >
          <AntdInput
            maxlen={500}
            disabled={disabled}
            
            rows={3}
            type="textarea"
            placeholder="请输入不超过500字符"
            
          />
          {/* <TextArea rows={4} disabled={disabled} /> */}
        </AntdFormItem>,
      ],
    ];
    return (
      <div>
        {mode == 'edit' ? (
          <AntdForm>{formItemFragement(formItem)}</AntdForm>
        ) : (
          visible && (
            <AdModal
              visible={visible}
              title={detail.id ? '编辑' : '新增' + '中港放空档案'}
              onOk={this.saveInfo}
              onCancel={() => {
                modalEmpty();
              }}
              width="60%"
              style={{
                maxWidth: 600,
              }}
            >
              <div className={styles.cusModal}>
                <AntdForm>{formItemFragement(formItem)}</AntdForm>
              </div>
            </AdModal>
          )
        )}
      </div>
    );
  }
}
